/*
 * Copyright (C) 2007-2008  Alessandro Melandri
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * */

package net.melandri.jtextfileparser.beans;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import net.melandri.jtextfileparser.utils.FileManager;

/**
 * @author Alessandro Melandri
 * @version 1.0
 * 
 * Class for reading and writing text files
 * */
public class TextFileManager {

	private BufferedReader buffReader;
	private FileWriter filewriter;
	private BufferedWriter writer;
	
	String SEP;
	
	private String filePath;
	private String fileName;
	private String fullPath;
	
	
	/**
	 * Loads the text file from the file system
	 * 
	 * @param fileName 	Text file name
	 * @param filePath 	Text file path
	 * @param sep 		Fields separator
	 * 
	 * @throws FileNotFoundException if the text file is not found
	 * */
	protected TextFileManager(String fileName, String filePath, String sep) throws FileNotFoundException {
		
		this.fileName = fileName;
		this.filePath = filePath;
		SEP = sep;
		
		this.fullPath = FileManager.composeFilePath(this.fileName, this.filePath);
		
		buffReader = FileManager.loadTextFile(fullPath);
	}

	
	
	/**
	 * Parses the file and returns an ArrayList of Row objects
	 * 
	 * @return Retuns an ArrayList of Row objects
	 * */
	protected ArrayList read(){
		
		ArrayList file = new ArrayList();
		String textRow = null;
		
		int rowCounter = 1;
		
		try {
			
			while ((textRow = buffReader.readLine()) != null){
	
				if(!textRow.trim().equals("")){
					Row thisRow = parseRow(textRow,rowCounter);
					file.add( thisRow );
				}

				rowCounter++;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return file;
	}
	
	
	
	/**
	 * Generates a text file from an ArrayList of Rows
	 * 
	 * @param rows		Rows to be included in the new file
	 * @param fileName 	The name of the file to be created
	 * @param filePath 	The path where the file will be created
	 * */
	protected void write(ArrayList rows, String fileName, String filePath){
		
		createFile(fileName,filePath);
		Iterator it = rows.iterator();
		
		try {
			while(it.hasNext()){
				Row row = (Row)it.next();
				
				String stringRow = "";
				
				if (row.getSimpleRow() != null){
					stringRow = row.getSimpleRow();
				}
				else{
					String[] fields = row.getFields();
					for (int i = 0 ; i < fields.length ; i++){
						stringRow += fields[i];
						
						if (i != fields.length-1)
							stringRow += SEP;
					}
				}
				this.writer.write(stringRow + "\n");
				this.writer.flush();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				this.writer.close();
				this.filewriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	/**
	 * Generates a text file from an ArrayList of Rows using the specified fields separator
	 * 
	 * @param rows		Rows to be included in the new file
	 * @param fileName 	The name of the file to be created
	 * @param filePath 	The path where the file will be created
	 * @param sep		Fields separator
	 * */
	protected void write(ArrayList rows, String fileName, String filePath, String sep){
		
		createFile(fileName,filePath);
		Iterator it = rows.iterator();
		
		try {
			while(it.hasNext()){
				Row row = (Row)it.next();
				
				String stringRow = "";
				
				
				String[] fields = row.getFields();
				
				for (int i = 0 ; i < fields.length ; i++){
					stringRow += fields[i];
					
					if (i != fields.length-1)
						stringRow += sep;
				}
				
				this.writer.write(stringRow + "\n");
				this.writer.flush();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				this.writer.close();
				this.filewriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	/**
	 * Parses a row and returns a Row object
	 * 
	 * @param textRow 	 The original text row
	 * @param rowNumber The row number in the text file.
	 * 
	 * @return Returns a row object containing the content of the row parsed
	 * */
	protected Row parseRow(String textRow, int rowNumber){
		
		Row row = new Row(SEP);
		row.setNumber(rowNumber);
		row.setFields(textRow.split(SEP));
		
		return row;
	}
	
	
	/**
	 * Creates a file on the file system and sets up the BufferedWriter
	 * 
	 * @param fileName Name of the file
	 * @param filePath Path of the file
	 * */
	private void createFile(String fileName, String filePath){
		
		String fullPath = FileManager.composeFilePath(fileName, filePath);
		
		try {
			this.filewriter = new FileWriter(fullPath);
			this.writer = new BufferedWriter(filewriter);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}